package com.itany.shop.service.impl;

import com.itany.mybatis.factory.ObjectFactory;
import com.itany.mybatis.tm.TransactionManager;
import com.itany.shop.dao.UserMapper;
import com.itany.shop.entity.User;
import com.itany.shop.entity.UserExample;
import com.itany.shop.exception.ServiceException;
import com.itany.shop.exception.ShopException;
import com.itany.shop.service.UserService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;
import java.util.List;

/**
 * Description: 类的描述
 * Author: liudaolin@itany.com
 * Date: 2021/07/21 15:52
 * Version: 1.0 版本信息
 */
public class UserServiceImpl implements UserService {
    @Override
    public void register(User user, String rePassword) throws ShopException {
        // 业务处理
        // 密码判断
        if (!rePassword.equals(user.getPwd())) {
            throw new ShopException("两次输入的密码不一致");
        }
        // 用户名是否重复
        UserMapper userDao = ObjectFactory.getObj("userDao");

        UserExample example = new UserExample();
        // 添加条件, 根据用户名查询
        example.or().andLoginNameEqualTo(user.getLoginName());
        List<User> users = userDao.selectByExample(example);
        if (!users.isEmpty()) {
            throw new ShopException("该用户名已存在, 不能被重复注册");
        }

        // 核心操作
        userDao.insertSelective(user);
    }


    @Override
    public void login(User user) throws ShopException, ServiceException {
        UserMapper um = ObjectFactory.getObj("userDao");

        // TODO 用户名密码校验

        // TODO 登录
        UserExample example = new UserExample();
        UserExample.Criteria or = example.or();
        or.andLoginNameEqualTo(user.getLoginName());
        or.andPwdEqualTo(user.getPwd());
        List<User> users = um.selectByExample(example);
        if (users.isEmpty()) {
            throw new ShopException("帐号或者密码错误");
        }
    }


    private boolean check(String val) {
        return val == null || val.trim().isEmpty();
    }


    TransactionManager tm;

    @Before
    public void before() {
        tm = ObjectFactory.getObj("tm");
        tm.begin();

    }

    @After
    public void after() {
        tm.commit();
    }

    @Test
    public void testLogin() {
        User user = new User();
        user.setLoginName("刘亦菲");
        user.setPwd("1234");
        try {
            login(user);
            System.out.println("登录成功");
        } catch (ShopException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testRegister() {
        System.out.println("Hello");
        User user = new User();
        user.setLoginName("刘亦菲");
        user.setNickname("蛋卷");
        user.setPhone("110");
        user.setPwd("123");
        user.setCreateDate(new Date());

        try {
            register(user, "123");
        } catch (ShopException e) {
            e.printStackTrace();
        }
    }
}
